package com.zirenx.sys.controller;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.druid.util.StringUtils;
import com.jfinal.aop.Inject;
import com.jfinal.core.ActionKey;
import com.jfinal.core.Controller;
import com.zirenx.annotation.RouteMapping;
import com.zirenx.common.config.ConstantConfig;
import com.zirenx.common.controller.BaseController;
import com.zirenx.common.exception.MessageException;
import com.zirenx.sys.model.SysFile;
import com.zirenx.sys.model.SysMenu;
import com.zirenx.sys.model.SysUser;
import com.zirenx.sys.service.SysFileService;
/**
 * IndexController 指向系统访问首页
 * @author jbolt.cn
 * @email 909854136@qq.com
 * @date 2018年11月4日 下午9:02:52
 */
import com.zirenx.sys.service.SysLogService;
import com.zirenx.sys.service.SysMenuService;
import com.zirenx.sys.service.SysUserService;
import com.zirenx.utils.LogUtils;
import com.zirenx.utils.MD5Utils;
import com.zirenx.utils.SysUserUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

import javax.servlet.http.HttpServletRequest;

@RouteMapping("")
public class IndexController extends BaseController {
	
	@Inject
	SysMenuService sysMenuService;
	@Inject
	SysFileService sysFileService;
	@Inject
	SysUserService sysUserService;
	@Inject
	SysLogService sysLogService;
	
	/**
	 * 首页Action
	 */
	public void index() {
		try{
			List<SysMenu> list = null;
			Long userId = SysUserUtils.getUserId(getRequest());
			//是否拥有所有权限
			boolean isSuper = sysUserService.isSuper(userId);
			if (isSuper){
				list = sysMenuService.getMenus();
			}else {
				list = sysMenuService.getMenusByUserId(userId);
			}

			SysUser user = SysUserUtils.getUser(getRequest());

			String picUrl = "/static/img/photo_s.jpg";
			if(user.getPicId()!=null) {
				SysFile sysFile = sysFileService.getDao().findById(user.getPicId());
				picUrl = sysFile.getUrl();
				File file = new File(ConstantConfig.UPLOAD_PATH + picUrl);
				if (!file.exists()){
					picUrl = "/static/img/photo_s.jpg";
				}
			}
			setAttr("picUrl", picUrl);

			setAttr("user", user);
			setAttr("menuList", list);

		}catch (Exception e){
			LogUtils.error(this.getClass(),e);
		}
		render(ConstantConfig.ADMIN_PATH + "index_v1.html");
	}


	public void right() {
		render(ConstantConfig.ADMIN_PATH + "right.html");
	}

	/**
	 * 登录
	 */
	public void login() {
		HttpServletRequest request = getRequest();
		String operation = "进入登录";
		String content = "";
		try {
			String method = get("method");
			if(!StringUtils.isEmpty(method) && method.equals("post")) {
				operation = "提交登录";

				String username = get("username");
				String password = get("password");

				password = MD5Utils.encrypt(username, password);	//加密
				SysUser sysUser = sysUserService.login(username);
				if(sysUser == null) {
					throw new MessageException("用户名不存在");
				}

				//添加用户认证信息
				Subject subject = SecurityUtils.getSubject();
				UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
						username,password);

				//进行验证，这里可以捕获异常，然后返回对应信息
				subject.login(usernamePasswordToken);
				SysUserUtils.setUser(sysUser,request);
				sysLogService.saveLog(request, operation, "登录成功");

				redirect("/admin/index");
				return;
			}
		}catch (MessageException e) {
			content = e.getMessage();
			setAttr("errMsg", e.getMessage());
		} catch (Exception e) {
			content = "密码错误";
			LogUtils.error(this.getClass(),e);
			setAttr("errMsg", content);
		}

		sysLogService.saveLog(request, operation, content);
		render(ConstantConfig.ADMIN_PATH + "login.html");
	}

	/**
	 * 退出
	 */
	public void logout() {
		HttpServletRequest request = getRequest();
		String operation = "退出登录";
		String content = "退出成功";
		try {
			Subject subject = SecurityUtils.getSubject();
			subject.logout();//注销
			render(ConstantConfig.ADMIN_PATH + "login.html");
		} catch (Exception e) {
			index();
			content = "退出失败";
			LogUtils.error(this.getClass(), e);
		}

		sysLogService.saveLog(request, operation, content);
	}
}